<template>
  <div class="app-container">
    <div class="search-section card-section">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" style="margin-bottom: 10px;">
        <template v-for="(item, idx) in searchItems">
          <el-form-item v-if="showAllSearch || idx < 3" :key="item.prop" :label="item.label" :prop="item.prop">
            <component :is="item.component" v-model="queryParams[item.prop]" v-bind="item.attrs" @change="item.onChange && item.onChange($event)" />
          </el-form-item>
        </template>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable size="small" style="width: 120px">
            <el-option label="已付款" :value="1" />
            <el-option label="退款中" :value="2" />
            <el-option label="已退款" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button v-if="searchItems.length > 3" type="text" size="mini" @click="showAllSearch = !showAllSearch">
            <span v-if="!showAllSearch">更多 <i class="el-icon-arrow-down"></i></span>
            <span v-else>收起 <i class="el-icon-arrow-up"></i></span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-section card-section">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" border >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单类型" align="center" prop="type">
          <template slot-scope="scope">
            <span>{{ scope.row.type == 4 ? '人脸订单' : scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="房东姓名" align="center" prop="chName">
          <template slot-scope="scope">
            <span>{{ scope.row.chName || scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="chMobile" />
        <el-table-column label="支付IP" align="center" prop="payIp" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.orderStatus)" size="small">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="三方单号" align="center" prop="tradeNo" />
        <el-table-column label="商户订单" align="center" prop="orderNo" />
        <el-table-column label="金额" align="center" prop="totalPrice" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="260" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              @click="handleRefund(scope.row)"
              :disabled="scope.row.orderStatus == 0"
            >退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20" style="margin-bottom: 0;">
          <el-col :span="8">
            <el-form-item label="房东姓名" prop="chName">
              <el-input v-model="form.chName" placeholder="请输入房东姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="chMobile">
              <el-input v-model="form.chMobile" placeholder="请输入手机号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="margin-top: 8px; margin-bottom: 8px; font-weight: bold; color: #409EFF;">缴费地址信息</div>
        <div style="display: flex; flex-wrap: wrap; gap: 16px;">
          <el-card v-for="(item, idx) in form.details" :key="'edit-detail-' + idx" shadow="hover" style="width: 340px; margin-bottom: 8px;">
            <div style="font-weight: bold; color: #409EFF; margin-bottom: 8px;">缴费地址{{ idx + 1 }}
              <el-button type="text" icon="el-icon-delete" style="float: right; color: #F56C6C;" @click="removeDetail(idx)" v-if="form.details.length > 1">删除</el-button>
            </div>
            <el-form-item :label="'详细地址'" :prop="'details.' + idx + '.address'" label-width="70px">
              <el-input v-model="item.address" placeholder="请输入详细地址" clearable />
            </el-form-item>
            <el-form-item :label="'门牌'" :prop="'details.' + idx + '.door'" label-width="70px">
              <el-input v-model="item.door" placeholder="请输入门牌" clearable />
            </el-form-item>
            <el-form-item :label="'金额'" :prop="'details.' + idx + '.totalPrice'" label-width="70px">
              <el-input v-model="item.totalPrice" placeholder="请输入金额" clearable />
            </el-form-item>
          </el-card>
        </div>
        <el-button type="primary" icon="el-icon-plus" @click="addDetail" style="margin-top: 8px;">添加地址</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, submitRefund } from "@/api/door/order"
import { deptTreeSelect } from "@/api/system/user"

export default {
  name: "Info",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 4,
        chName: null,
        chMobile: null,
        country: null,
        addressNode: null,
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        address: null,
        door: null,
        totalPrice: null,
        orderStatus: 1, // 默认查询已付款状态
        payTime: null,
        tradeNo: null,
        orderNo: null,
        months: null,
        cardCount: null,
        plan: null
      },
      // 表单参数
      form: {
        id: null,
        createBy: null,
        createTime: null,
        type: 4,
        name: null,
        phone: null,
        addressNode: null,
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        address: null,
        door: null,
        totalPrice: null,
        orderStatus: null,
        payTime: null,
        tradeNo: null,
        orderNo: null,
        plan: null,
        details: [{ name: '', phone: '', door: '', address: '', plan: '', totalPrice: '' }]
      },
      // 表单校验
      rules: {
      },
      addressTreeOptions: [],
      deptOptions: undefined,
      enabledDeptOptions: undefined,
      showAllSearch: false,
      searchItems: [
        { label: '姓名', prop: 'chName', component: 'el-input', attrs: { placeholder: '请输入姓名', clearable: true, onkeyup: null } },
        { label: '手机号', prop: 'chMobile', component: 'el-input', attrs: { placeholder: '请输入手机号', clearable: true, onkeyup: null } },
        { label: '地址', prop: 'remark', component: 'el-input', attrs: { placeholder: '请输入地址', clearable: true, onkeyup: null } },
        { label: '三方单号', prop: 'tradeNo', component: 'el-input', attrs: { placeholder: '请输入三方单号', clearable: true, onkeyup: null } },
        { label: '商户订单', prop: 'orderNo', component: 'el-input', attrs: { placeholder: '请输入商户订单', clearable: true, onkeyup: null } },
        { label: '方案', prop: 'plan', component: 'el-input', attrs: { placeholder: '请输入方案', clearable: true, onkeyup: null } }
      ],
      // 临时存储待回显的addressNode
      _pendingAddressNode: null,
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    // 初始化searchItems中cascader的options
    this.syncSearchCascaderOptions()
  },
  watch: {
    addressTreeOptions(newVal) {
      this.syncSearchCascaderOptions()
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
        this.buildAddressTreeFromDeptTree()
        // 递归patch value为String（注意是node.value，不是node.id）
        const patchTreeValue = (tree) => {
          if (!Array.isArray(tree)) return
          tree.forEach(node => {
            node.value = String(node.value)
            if (node.children) patchTreeValue(node.children)
          })
        }
        patchTreeValue(this.addressTreeOptions)
        this.syncSearchCascaderOptions()
        // 如果有待回显的addressNode，赋值
        if (this._pendingAddressNode) {
          this.form.addressNode = this._pendingAddressNode
          this._pendingAddressNode = null
        }
      })
    },
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    buildAddressTreeFromDeptTree() {
      if (!this.deptOptions || this.deptOptions.length === 0) return
      const convertToAddressTree = (deptNodes) => {
        if (!deptNodes || deptNodes.length === 0) return []
        return deptNodes.map(dept => {
          const addressNode = {
            value: dept.id,
            label: dept.label,
            disabled: dept.disabled
          }
          if (dept.children && dept.children.length > 0) {
            addressNode.children = convertToAddressTree(dept.children)
          }
          return addressNode
        })
      }
      this.addressTreeOptions = [{
        value: 100,
        label: this.deptOptions[0].label || "公司",
        disabled: false,
        children: convertToAddressTree(this.deptOptions[0].children || [])
      }]
      this.syncSearchCascaderOptions()
    },
    handleAddressNodeSelect(value) {
      this.queryParams.province = value[0]
      this.queryParams.city = value[1]
      this.queryParams.district = value[2]
      this.queryParams.street = value[3]
      this.queryParams.village = value[4]
    },
    handleFormAddressNodeSelect(value) {
      this.form.province = value[0] ? String(value[0]) : null
      this.form.city = value[1] ? String(value[1]) : null
      this.form.district = value[2] ? String(value[2]) : null
      this.form.street = value[3] ? String(value[3]) : null
      this.form.village = value[4] ? String(value[4]) : null
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        type: 4,
        name: null,
        phone: null,
        addressNode: null,
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        address: null,
        door: null,
        totalPrice: null,
        orderStatus: null,
        payTime: null,
        tradeNo: null,
        orderNo: null,
        plan: null,
        details: [{ name: '', phone: '', door: '', address: '', plan: '', totalPrice: '' }]
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.details = [{ name: '', phone: '', door: '', address: '', plan: '', totalPrice: '' }]
      this.open = true
      this.title = "添加订单信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data
        if (!this.form.details || !this.form.details.length) {
          this.form.details = [{ name: '', phone: '', door: '', address: '', plan: '', totalPrice: '' }]
        } else {
          // 兼容老数据，补全字段
          this.form.details = this.form.details.map(item => ({
            name: item.name || '',
            phone: item.phone || '',
            door: item.door || '',
            address: item.address || '',
            plan: item.plan || '',
            totalPrice: item.totalPrice || ''
          }))
        }
        this.open = true
        this.title = "修改订单信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除订单信息编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('door/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    getDeptLabelById(id) {
      // 递归查找部门名称
      const findLabel = (list, id) => {
        for (let item of list) {
          if (item.id === id) return item.label
          if (item.children) {
            const found = findLabel(item.children, id)
            if (found) return found
          }
        }
        return ''
      }
      if (!id || !this.deptOptions) return ''
      return findLabel(this.deptOptions, id)
    },
    // 退款操作
    async handleRefund(item) {
      this.$modal.confirm(
        `确定要对此订单进行退款操作吗？\n订单号：${item.orderNo}\n金额：¥${item.totalPrice}`,
        '确认退款'
      ).then(async () => {
        try {
          this.$modal.loading('正在处理退款...')
          
          const data = {
            orderNo: item.orderNo
          }
          
          console.log('退款数据:', data)
          const response = await submitRefund(data)
          
          if (response.code === 200) {
            this.$modal.closeLoading()
            this.$modal.msgSuccess('退款申请已提交')
            // 刷新列表数据
            this.getList()
          } else {
            this.$modal.closeLoading()
            this.$modal.msgError(response.msg || '退款申请失败')
          }
        } catch (error) {
          this.$modal.closeLoading()
          console.error('退款申请失败:', error)
          this.$modal.msgError('网络异常，请稍后重试')
        }
      }).catch(() => {})
    },
    // 保证搜索区域el-cascader的options和addressTreeOptions同步
    syncSearchCascaderOptions() {
      this.searchItems.forEach(item => {
        if (item.prop === 'addressNode') {
          item.attrs.options = this.addressTreeOptions
        }
      })
    },
    addDetail() {
      this.form.details.push({ name: '', phone: '', door: '', address: '', plan: '', totalPrice: '' })
    },
    removeDetail(idx) {
      this.form.details.splice(idx, 1)
    },
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '已付款', 
        2: '退款中',
        3: '已退款'
      }
      return statusMap[status] || '未知状态'
    },
    // 获取订单状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',    // 待付款 - 橙色
        1: 'success',    // 已付款 - 绿色
        2: 'info',       // 退款中 - 蓝色
        3: 'danger'      // 已退款 - 红色
      }
      return typeMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.card-section {
  background: #fff;
  padding: 18px 24px 6px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 18px;
}
.table-section {
  padding: 0;
  margin-bottom: 0;
}
/* 搜索区域表单项间距优化 */
.search-section ::v-deep .el-form-item {
  margin-right: 60px;
  margin-bottom: 16px;
}
.search-section ::v-deep .el-form-item:last-child {
  margin-right: 0;
}
</style>
